C++ 无法绑定';std::ostream{aka std::basic_ostream<;char>;}';左值为';std::basic_ostream<;char>&&';

C++ 无法绑定';std::ostream{aka std::basic_ostream<;char>;}';左值为';std::basic_ostream<;char>&&';,c++,c++11,C++,C++11,关于这个标题有很多问题,但是没有一个对我有帮助,我也不太明白到底发生了什么 我试图创建一个生成随机单词的类。首先,我尝试将所有元音和辅音放在两个不同的静态向量中;但是,在测试该类时,我遇到以下错误: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' 为什么会这样?如何解决它?首先:声明函数以接受一个常量字母&,然

关于这个标题有很多问题,但是没有一个对我有帮助,我也不太明白到底发生了什么

我试图创建一个生成随机单词的类。首先,我尝试将所有元音和辅音放在两个不同的
静态向量中;但是,在测试该类时,我遇到以下错误:

cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'

为什么会这样?如何解决它?

首先:声明函数以接受一个
常量字母&
,然后定义您的成员静态变量,并在使用它之前向前声明或定义运算符

std::ostream& operator <<(std::ostream& os, const Letter& l);

class RandomWordGenerator {
    public:
        RandomWordGenerator() {
            vowels.push_back(Letter('A'));
        }
        static Word generate() {
            std::cout << vowels.front() << std::endl; // the error pops here
            Word w(std::string("test"));
            return w;
        }
    public:
        static std::vector<Letter> vowels;
        static std::vector<Letter> consonants;
};

std::vector<Letter> RandomWordGenerator::vowels;

std::ostream& operator <<(std::ostream& os, const Letter& l) {
    return os << l.inner(); // a std::string
}

std::ostream&operator类
Letters
重载操作符@awesomeyi哦,是的,我忘记发布了
的什么
要么在
RandomNumberGenerator
之前声明操作符,要么在操作符定义之后定义
生成
。@0x499602D2现在可以了!谢谢你能解释一下为什么会发生这种情况,为什么这是答案中的解决方案吗?你能解释一下为什么有必要向前声明这个方法,为什么不这样做会抛出一个错误吗?我正在添加一些细节以及一个链接到你应该看的帖子
std::ostream& operator <<(std::ostream& os, const Letter& l);

class RandomWordGenerator {
    public:
        RandomWordGenerator() {
            vowels.push_back(Letter('A'));
        }
        static Word generate() {
            std::cout << vowels.front() << std::endl; // the error pops here
            Word w(std::string("test"));
            return w;
        }
    public:
        static std::vector<Letter> vowels;
        static std::vector<Letter> consonants;
};

std::vector<Letter> RandomWordGenerator::vowels;

std::ostream& operator <<(std::ostream& os, const Letter& l) {
    return os << l.inner(); // a std::string
}
std::ostream& operator <<(std::ostream& os, const Letter& l) {
    return os << l.inner(); // a std::string
}

class RandomWordGenerator {
    public:
        RandomWordGenerator() {
            vowels.push_back(Letter('A'));
        }

        friend std::ostream& operator <<(std::ostream& os, const Letter& l);

        static Word generate() {
            std::cout << vowels.front() << std::endl; // the error pops here
            Word w(std::string("test"));
            return w;
        }


    public:
        static std::vector<Letter> vowels;
        static std::vector<Letter> consonants;
};

std::vector<Letter> RandomWordGenerator::vowels;