子类构造函数不存储对象的数据

时间:2015-04-18 17:22:54

标签: c++ oop inheritance subclass

我正在尝试创建超类“Entry”的子类,它存储例如借用的库项目的信息。使用我的main来测试这些结果,没有为'name'和'artist'返回值,但它确实返回了超类变量'borrowedBy'的值。我认为在构造函数中使用它们会将值传递给对象,但我似乎在某处犯了一个错误。  头文件:

#include <iostream>
#include <string>

class Entry{
private:
    int borrowed;
    std::string borrowedBy;
public:
    Entry();
    void printDetails();
    std::string getborrowedBy();
};

class MusicAlbum : public Entry{
private:
    std::string name;
    std::string artist;
public:
    void printDetails();
    MusicAlbum(std::string name, std::string artist);
    ~MusicAlbum();
    std::string getname();
};

cpp文件:

#include <iostream>
#include <string>
#include "C2.h"

MusicAlbum::MusicAlbum(std::string name, std::string artist){
    std::cout << "Constructor..." << std::endl;
    std::cout << "Name: " << name << std::endl;
    std::cout << "Artist: " << artist << std::endl << std::endl;
}

MusicAlbum::~MusicAlbum(){};

std::string MusicAlbum::getname(){
    return name;
};

std::string Entry::getborrowedBy(){
    return borrowedBy;
};

Entry::Entry(){
    borrowed = 1;
    borrowedBy = "test1";
};

void MusicAlbum::printDetails(){
    std::cout << "Printer..." << std::endl;
    std::cout << "Name: " << name << std::endl;
    std::cout << "Artist: " << artist << std::endl << std::endl;
}

int main(){
    MusicAlbum MA1("Name1", "Artist1");
    MA1.printDetails();
    std::cout << "getname: " << MA1.getname() << std::endl << std::endl;
    std::cout << "getborrowedby: " << MA1.getborrowedBy() << std::endl << std::endl;
    system("pause");
    return 0;
}

运行程序提供以下内容:

Constructor...
Name: Name1
Artist: Artist1

Printer...
Name:
Artist:

getname:

getborrowedby: test1

因此,似乎存储了来自'Entry'构造函数的信息,而不是来自'MusicAlbum'构造函数的信息。 其次,在定义一个新对象时,是否可以在保持私有的同时更改值“borrowedBy”?它在MusicAlbum构造函数中“无法访问”。

1 个答案:

答案 0 :(得分:0)

您必须更改构造函数以初始化类成员变量。由于变量的名称,没有任何内容自动完成:

MusicAlbum::MusicAlbum(std::string name, std::string artist) 
         : name(name), artist(artist) {
     ...
}

name(name)表示使用参数name(内部名称)初始化类成员name(外部名称)。

请注意,此初始化列表还允许指定基类的参数。例如,如果你有一个基础构造函数:

Entry::Entry(std::string borrower) 
    :  borrowedBy(borrower), borrowed(1)
{ };

然后你也可以有一个派生的构造函数,如:

MusicAlbum::MusicAlbum(std::string name, std::string artist, std::string bywhom) 
         : name(name), artist(artist), Entry (bywhom) {
     ...
}
相关问题