gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:05:35 24 4
gpt4 key购买 nike

我有两条简单的测试线:

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/

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