小编Rob*_*ert的帖子

为什么我不能访问派生构造函数的成员初始化列表中继承的受保护字段?

我是 OOP 的新手。最近学习了C++中继承的一些东西,一个protected字段不能从类外访问,但是可以在继承的类中访问。我的代码有一些问题,我不明白出了什么问题:

class Base
{
protected:
    int x;
    int y;
    int z;
public:
    Base(int a, int b): x(a), y(b) { cout << "Base constructor" << endl; };
    Base(const Base& prev) : x(prev.x), y(prev.y) { cout << "Base copy constructor" << endl; };

    void print_x()
    {
        cout << x << endl;
    }

    void print_y()
    {
        cout << y << endl;
    }

    ~Base() { cout << "Base destructor" << endl; };
};

class Derived : public Base
{
public: …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance class

2
推荐指数
1
解决办法
73
查看次数

为什么我们使用 const 和 reference 作为参数来复制构造函数?

考虑以下示例:

#include<iostream> 
using namespace std;

class Point
{
private:
    int x, y;
public:
    Point(int x1, int y1) { x = x1; y = y1; }

    // Copy constructor 
    Point(const Point& p2) { x = p2.x; y = p2.y; }

    int getX() { return x; }
    int getY() { return y; }
};

int main()
{
    Point p1(10, 15); 
    Point p2 = p1; 


    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
    cout << "\np2.x = …
Run Code Online (Sandbox Code Playgroud)

c++ constructor class

0
推荐指数
1
解决办法
66
查看次数

标签 统计

c++ ×2

class ×2

constructor ×1

inheritance ×1