期末复习C++遇到的问题
1.指针类型成员初始化
#include<iostream>
using namespace std;
class A
{
public:
A():p(new char('a')){}
A(const A&s):p(new char(*s.p)){}
private:
char* p;
};
int main()
{
A a;
A a1 = a;
}
2.运算符重载
详细说明
3.拷贝构造的继承
#include<iostream>
using namespace std;
class A {
public:
A(int x) { a = x; }
A(const A& obj) { a = obj.a; }
A& operator = (A& obj)
{
if (this == &obj)
return *this;
a = obj.a;
return *this;
}
protected:
int a;
};
class B : public A {
public:
B(int, int);
B(const B&);
B& operator=(B&);
void print()
{
cout << a << " " << b << endl;
}
private:
int b;
};
B::B(int x, int y) :A(x), b(y) {}
B::B(const B& obj) : A(obj) {
b = obj.b;
}
B& B::operator = (B& obj)
{
if (this == &obj)
return *this;
a = obj.a;
b = obj.b;
return *this;
}
int main()
{
A a(8);
B b1(10, 23);
B b2 = b1;
b2.print();
B b3(0, 0);
b3 = b2;
b3.print();
return 0;
}
4.覆写私有函数,覆写静态成员函数
#include<iostream>
using namespace std;
class A {
public:
A() { }
static int getC() { return c; }
private:
int a;
void f() { cout << '1' << endl; }
protected:
static int c;
};
class B : public A {
public:
B() { c++; }
static int getC()
{return c;}
void f() { cout << '2' << endl; }
};
int A::c = 0;
int main()
{
B b;
b.f();
cout << B::getC() << endl;
return 0;
}
原文地址:https://blog.csdn.net/qq_43593646/article/details/103721450
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!