gpt4 book ai didi

c++ - 使用 operator<< 重载打印派生对象不起作用

转载 作者:行者123 更新时间:2023-11-28 06:49:35 24 4
gpt4 key购买 nike

为什么我不能使用这种方法打印派生对象?我怎样才能解决这个问题,以便派生打印输出打印“派生大小=8”。理想情况下,我希望将打印代码保留在类代码之外。

#include <iostream>

class base
{
public:
base(int size) : size_(size) {}

virtual int get_size() const { return size_; }

private:
int size_;
};

std::ostream& operator<<(std::ostream& os, const base& obj) {
os << "base size=" << obj.get_size() << std::endl;
return os;
}

class derived1 : public base
{
public:
derived1(int size) : base(size) {}

virtual int get_size() const {
return 2 * base::get_size();
}
};

std::ostream& operator<<(std::ostream& os, const derived1& obj) {
os << "derived1 size=" << obj.get_size() << std::endl;
return os;
}

int main(int argc, char* argv[]) {

base* b1 = new base(3);
std::cout << "b1 size is: " << b1->get_size() << std::endl;

std::cout << *b1 << std::endl;

base* b2 = new derived1(4);
std::cout << "b2 size is: " << b2->get_size() << std::endl;

std::cout << *b2 << std::endl;

delete b1;
delete b2;
return 0;
}

Output:
b1 size is: 3
base size=3

b2 size is: 8
base size=8

更新:

我根据有效的 ghostsofstandardspast 进行了如下更改:

#include <iostream>

class base
{
public:
base(int size) : size_(size) {}

virtual int get_size() const { return size_; }
friend std::ostream& operator<<(std::ostream &os, const base& obj);

private:
virtual std::ostream &print(std::ostream &os) const {
return os << "base size=" << get_size() << std::endl;
}

int size_;
};

std::ostream& operator<<(std::ostream& os, const base& obj) {
obj.print(os);
return os;
}

class derived1 : public base
{
public:
derived1(int size) : base(size) {}

virtual int get_size() const {
return 2 * base::get_size();
}

friend std::ostream& operator<<(std::ostream &os, const derived1& obj);
private:
virtual std::ostream &print(std::ostream &os) const {
return os << "derived1 size=" << get_size() << std::endl;
}
};


int main(int argc, char* argv[]) {

base* b1 = new base(3);
std::cout << "b1 size is: " << b1->get_size() << std::endl;

std::cout << *b1 << std::endl;

base* b2 = new derived1(4);
std::cout << "b2 size is: " << b2->get_size() << std::endl;

std::cout << *b2 << std::endl;
return 0;
}

最佳答案

operator<<不是虚成员函数,因此它不能像其他成员函数那样以多态方式使用。相反,您应该委托(delegate)给虚拟成员。

同时更改您的 operator<<重载到名为 print 的虚拟成员函数或类似的东西。然后,重载 operator<<委托(delegate)给那个:

std::ostream &operator<<(std::ostream &os, const Base &obj) {
obj.print(os); //or whatever name you choose
return os;
}

如果你想使成员函数私有(private),使operator<<一个 friend 。

最后,请注意,打印指向您的类对象的指针只会打印地址。调用 operator<< ,您需要打印对象本身:

Base *b = /*whatever*/;
std::cout << *b;

此技术用于多态 operator<<this cppquiz question 中展示.我强烈建议您完成这些问题。

关于c++ - 使用 operator<< 重载打印派生对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24232130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com