c++ - 如何在逗号运算符中包含声明?

标签 c++ operators declaration

我有两条简单的测试线:

cout<<(cout<<"ok"<<endl, 8)<<endl;

cout<<(int i(8), 8)<<endl;

第一行有效,但第二行编译失败

error: expected primary-expression before 'int'

出于某种原因,我确实需要在逗号运算符中声明。更具体地说,我想声明一些变量,获取它们的值,并将它们分配给类构造函数的初始化列表中的常量类成员。以下显示了我的意图。如果使用逗号运算符无法实现,还有其他建议吗?

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>

using namespace std;

void readFile(const string & fileName, int & a, int & b)
{
    fstream fin(fileName.c_str());
    if (!fin.good()) {cerr<<"file not found!"<<endl; exit(1);}
    string line;
    getline(fin, line);
    stringstream ss(line);
    try {ss>>a>>b;}
    catch (...) {cerr<<"the first two entries in file "<<fileName<<" have to be numbers!"<<endl; exit(1);}
    fin.close();
}

class A
{
    private:
        const int _a; 
        const int _b; 
    public:
        A(const string & fileName)
            :   
            _a((int a, int b, readFile(fileName,a,b), a)),
            _b((int a, int b, readFile(fileName,a,b), b)) 
        {   
            /*  
            int a, b;
            readFile(fileName,a,b);
            _a = a;_b = b;
            */
        }   

        void show(){cout<<_a<<" "<<_b<<endl;}
};

int main()
{
    A a("a.txt");
    a.show();
}

最佳答案

声明是语句而不是表达式。不能将语句放在表达式内,但可以将表达式放在语句内。因此,您不能按照上面描述的方式声明变量。您需要将其分成多个不同的语句。

如果您真的需要这样做,我会感到很惊讶。如果这样做,则您的设计可能存在问题。

希望这对您有所帮助!

关于c++ - 如何在逗号运算符中包含声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17708225/

相关文章:

c++ - SSE 移位指令在后续指令中导致奇怪的输出 (-1.#IND00)?

c# - 在 C# 中使用自定义 F# 运算符?

java - A *= B *= A *= B 是怎么求值的?

python - 那么 “from __future__ import barry_as_FLUFL” 究竟是做什么的呢?

c++ - 如何声明一个采用模板类的嵌套类的全局友元函数?

定义数组后,我可以通过用户输入在数组的括号/参数内定义变量吗?

用 auto 定义的变量的 C++11 类型

c++ - Windows x86的PostgreSQL 11安装程序?

c - 返回函数指针的函数声明

c++ - 使用 std::equal 和相等运算符的比较