课程疑问小结

1.类的问题

有两个类X和Y,X中有一个数据成员为指向Y的指针,Y中有一个数据成员是X的对象。
代码:

#ifndef PRACTICE_2_H
#define PRACTICE_2_H

/*
 * 2016/5/21
 */

class Y;//需要在class X的声明前声明class Y的存在

class X
{
	public:
	    Y *p;
};

class Y
{
	public:
		X x1;
};

#endif // PRACTICE_2_H

2.全局定义类的对象并对该对象中元素赋值的错误问题

错误代码如下:(main.cpp)

#include "practice.h" // class's header file
#include <iostream>
using namespace std;

Student stu1;
stu1.a = 1;//在main函数外赋值
int main()
{
	cout << stu1.a << endl;
	
	return 0;
}

编译器错误提示:

???

更新:刚刚开始非常懵逼,考虑了类的作用域的范围还有刚刚开始调用构造函数和析构函数的对象作用域的存在周期。然后突然发现应该和C的相关知识有关。
于是我写了如下代码:

#include <cstdio>
int a;
a = 1; //error
int main()
{
	printf("%d
",a);
	return 0;
}

编译错误。终于找到了答案:

“main函数之前是用来声明和定义全局变量和函数的,并由编译器进行预处理,给那些全局变量和定义的函数分配内存和地址,不能设计可执行代码。”

参考链接:戳这里

3.利用构造函数对数据成员进行初始化的小练习

main.cpp

#include "practice_3.h" // class's header file
#include <iostream>
using namespace std;

int main()
{
	practice_3 p;
	
	int data;
	cin >> data;
	
	p.fun(data);
	p.display();
	
	return 0;
}

practice_3.h

#ifndef PRACTICE_3_H
#define PRACTICE_3_H

class practice_3
{
	private:
		int data;
	public:
		void fun(int a = 10);
		void display();
	//protected:
};

#endif // PRACTICE_3_H

practice_3.cpp

#include "practice_3.h" // class's header file
#include <iostream>
using namespace std;

void practice_3::fun(int a)
{
	data = a;
}

void practice_3::display()
{
	cout << data << endl;
}

4.何谓obj文件?

百度:程序编译时生成的中间代码文件。目标文件,一般是程序编译后的二进制文件,再通过链接器和资源文件链接就成可执行文件了。OBJ只给出了程序的相对地址,而可执行文件是绝对地址。

貌似这个说法比较更加能够理解:obj就是目标文件,是你的源程序经过编译程序编译后生成的,它不能直接执行,需要连接程序连接后才能生成可执行文件。

原文地址:https://www.cnblogs.com/qq952693358/p/5515149.html