C++ 多继承 初步

#include <string>
#include <iostream>
using namespace std;
class Base {
public:
	char* m_name;
	int m_age;
	Base() {
		cout << "Base no pattern create" << endl;
		const char* nametemp = "def";
		this->m_name = new char[strlen(nametemp) + 1];
		strcpy(this->m_name, nametemp);
		this->m_age = 18;
	}
	Base(const char *name, int age) {
		cout << "Base use pattern create" << endl;
		this->m_name = new char[strlen(name) + 1];
		strcpy(this->m_name, name);
		this->m_age = age;
	}
	Base(const Base & b) {
		cout << "Base copy create" << endl;
		this->m_name = new char[strlen(b.m_name) + 1];
		strcpy(this->m_name, b.m_name);
		this->m_age = b.m_age;
	}
	Base& operator=(const Base & b) {
		cout << "Base = fun" << endl;
		if (this->m_name != NULL) {
			delete[] this->m_name;
		}
		this->m_name = new char[strlen(b.m_name) + 1];
		strcpy(this->m_name, b.m_name);
		this->m_age = b.m_age;
		return *this;
	}
	~Base() {
		cout << "Base delete" << endl;
		if (this->m_name != NULL) {
			delete[] this->m_name;
			this->m_name = NULL;
		}
	}
};

class Son : public Base {
public:
	int m_id;
	/*Son() { // 这样报错,父类没有默认构造函数(如果把父类的默认构造注释的话)

	}*/

	
	
};
void test1() {
	/*Son s;
	cout << s.m_age << endl;*/
	//Son s; // 这样会调用父类的无参构造
	//Son s1(s);  // 这样会调用父类的拷贝构造
	//Son s("Tom", 2); // 这样报错, 因为子类根本不会继承父类的构造函数
}
void test2() {
	//Son s; // 这样会调用父类的无参构造
	Son s;
	//s.m_name = const_cast<char *>("aab"); // 这样会导致程序崩溃
	//Son s1;
	//s1.m_name = const_cast<char*>("bbb");
	//s = s1;

	char* name = const_cast < char*>("AAa");
	s.m_name = new char[strlen(name) + 1];
	strcpy(s.m_name, name);
	
	Son s1;
	char* name1 = const_cast <char*>("AAa");
	s1.m_name = new char[strlen(name1) + 1];
	strcpy(s1.m_name, name);

	s = s1;

}
int main()
{
	//test1();
	test2();
	return 0;
}
发布了100 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43903378/article/details/103936996