期末复习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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值