gpt4 book ai didi

c++ - 无法理解与模板和构造函数相关的错误

转载 作者:太空狗 更新时间:2023-10-29 21:18:12 27 4
gpt4 key购买 nike

#include <iostream>
#include <vector>
#include <string>

using namespace std;

enum class demo_initialize { a = 1, b, c, d };

class Base {
public:
Base(demo_initialize initialize) : mInitialize(initialize) {}

protected:
demo_initialize mInitialize;
};

template <typename T>
class Derived : public Base
{
public:
Derived(T &value, demo_initialize initialize = demo_initialize::a) : Base(initialize), mValue(value), mLen(sizeof(T))
{
}

void display() {
cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";
}
protected:
T &mValue;
size_t mLen;
};

int main()
{
string string_to_reference = "world";
Derived<string> obj(string_to_reference, demo_initialize::c);
obj.display();

}

我正在尝试这段代码。编译时我在这一行出错:

cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";

错误是

In instantiation of 'void Derived<T>::display() [with T =   std::basic_string<char>]':
37:17: required from here
26:49: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/iostream:39:0,
from 1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = demo_initialize]'
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

我无法理解这个错误。有人可以帮我解决这个问题吗?

最佳答案

Base::mInitialize 不会自动转换为行中的 int

cout << "Derived<T>{" << mValue << "; " << Base::mInitialize << "}";

使用:

cout << "Derived<T>{" << mValue << "; " << static_cast<int>(Base::mInitialize) << "}";

关于c++ - 无法理解与模板和构造函数相关的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30723036/

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