2017-09-03 164 views

回答

1

您似乎对变量如何在C++中工作感到困惑。

使用GCC编译程序时,它说:

test.cpp: In function ‘int main()’: 
a.cpp:23:20: error: ‘email’ was not declared in this scope 
      cin >> email; 

这意味着,有一个名为email没有这样的变量。您在emailverify类中声明了具有该名称的成员变量,但只有在您定义类型为emailverify的变量时才会使用该变量,但您没有这样做。

现在,我建议你摆脱emailverify类,并声明需要直接与局部变量在main变量(你可以声明他们作为全球性的,但它是,如果你让他们更好的地方):

int main() 
{ 
    std::string test; 
    std::string email; 
    std::string at = "@"; 
    std::string period = "."; 

然后还有一大堆其他错误,诸如email.find(at != std::string::npos)代替email.find(at) != std::string::npos,但你会得到那些最终。 PS:我知道一些编程老师喜欢编写代码,如std::string at = "@";,但恕我直言,这只是愚蠢的。写作email.find("@")是完全正确的,额外的变量买你什么都没有。

+0

非常感谢!我只是试图使用这门课,因为我们的老师建议我们使用它。 –

+0

@ A.j.Schenker:啊,我看不出一个班级在这里有用。但是如果你想尝试一下,你必须定义一个类的变量'int main(){emailverify e;',然后引用成员变量为'e.test','e.email'等。但是要小心你声明的那个本地'test'变量,这与'e.test'不同。 – rodrigo

0

你的问题是部分代码:

class emailverify 
{ 
public:    // global variables/functions 
    std::string test; 
    std::string email; 
    std::string at = "@"; 
    std::string period = "."; 
}; 

定义全局变量或函数,但声明类。没有定义或声明主函数中的电子邮件或测试变量。

如果你想坚持到全局的东西,你所能做的就是创造型emailverify的全局对象,并通过.使用其成员或使所有的人static,并获得通过::emailverify::test)或改变classnamespace,但它需要在课堂外定义它们(Defining static members in C++)。

但是,您可以将它们当作当地人使用,不必担心所有这些。

+0

我只是试图做到这一点,并没有足够理解它能够实现全局变量。 :/谢谢! –