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

Hai*_*ang 1 c++ declaration operators

我有两个简单的测试线:

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

cout<<(int i(8), 8)<<endl;
Run Code Online (Sandbox Code Playgroud)

第一行工作,但第二行编译失败

error: expected primary-expression before 'int'
Run Code Online (Sandbox Code Playgroud)

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

#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();
}
Run Code Online (Sandbox Code Playgroud)

tem*_*def 6

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

如果你真的要这样做,我会感到惊讶.如果你这样做,你的设计可能会出现问题.

希望这可以帮助!


asc*_*ler 5

lambda允许在表达式中声明.所以这是可能的:

std::cout << ([]{ int i(8); m_i = i; }(), 8) << std::endl;
Run Code Online (Sandbox Code Playgroud)

但它真的很奇怪 - 我认为这将在一些#define宏观中使它看起来更接近正常.


seh*_*ehe 5

你应该看看Boost Phoenix(它有凤凰::让我们大致这样做).请记住,Phoenix是一个eDSL,真的是(嵌入式域特定语言).

你可以做一个丑陋的伎俩和虐待lambdas:

cout<< ([]->int{ int i(8); return 8; })() <<endl;
Run Code Online (Sandbox Code Playgroud)

  • @GrijeshChauhan,是的,lambdas(代码示例,而不是Boost)是C++ 11. (2认同)
  • 只能推断出身体中只有"return"语句. (2认同)