class 中只有一个函数在 c++ 的主要函数中被使用
only one function from class intilized in main function of c++
我刚刚写了一个简单的程序,在 class 中有两个函数。问题是当我从 main()
调用它们时,只有第一个函数执行并且程序终止而没有调用第二个函数。
#include <stdio.h>
#include <iostream>
using namespace std;
class exp{
public:
string name;
public:
string fun1(){
cout<<"please enter value for first function ";
cin>>name;
cout<<"yourname from first function is ";
cout<<name;
return 0;
}
string fun2(){
cout<<"Please enter value for second function ";
cin>>name;
cout<<"yourname from second function is ";
cout<<name;
return 0;
}
};
int main(){
exp b1,b2;
cout << b2.fun1();
cout << b1.fun2();
}
输出为
please enter value for first function preet
yourname from first function is preet
您正在 returning 0
,而 return 类型是 string
。不允许从空指针构造 std::string
。您可以改用 return "";
。
在这里,试试这个
#include <stdio.h>
#include<iostream>
using namespace std;
class exp
{
private: // changed from public to private
string name;
public:
int fun1() // changed from string to int
{
cout<<"\nplease enter value for first function ";
cin>>name;
cout<<"\nyourname from first function is ";cout<<name<<endl;
return 0;
}
int fun2() // changed from string to int
{
cout<<"\nPlease enter value for second function ";
cin>>name;
cout<<"\nyourname from second function is ";
cout<<name<<endl;
return 0;
}
};
int main()
{
exp b1,b2;
b2.fun1(); // removed cout
b1.fun2(); // removed cout
}
问题是您在函数内部使用 cout
,但您也在函数内部调用它们,即 cout<<b2.fun1();
。这不是一个好的做法。
还有一个问题是你的函数类型是字符串,但它们返回的是一个整数。
您还把 name
设为 public
,这恰恰违背了 OOP 的使用。所以我做到了 private
.
干杯......希望这能解决你的问题.. :)
我刚刚写了一个简单的程序,在 class 中有两个函数。问题是当我从 main()
调用它们时,只有第一个函数执行并且程序终止而没有调用第二个函数。
#include <stdio.h>
#include <iostream>
using namespace std;
class exp{
public:
string name;
public:
string fun1(){
cout<<"please enter value for first function ";
cin>>name;
cout<<"yourname from first function is ";
cout<<name;
return 0;
}
string fun2(){
cout<<"Please enter value for second function ";
cin>>name;
cout<<"yourname from second function is ";
cout<<name;
return 0;
}
};
int main(){
exp b1,b2;
cout << b2.fun1();
cout << b1.fun2();
}
输出为
please enter value for first function preet
yourname from first function is preet
您正在 returning 0
,而 return 类型是 string
。不允许从空指针构造 std::string
。您可以改用 return "";
。
在这里,试试这个
#include <stdio.h>
#include<iostream>
using namespace std;
class exp
{
private: // changed from public to private
string name;
public:
int fun1() // changed from string to int
{
cout<<"\nplease enter value for first function ";
cin>>name;
cout<<"\nyourname from first function is ";cout<<name<<endl;
return 0;
}
int fun2() // changed from string to int
{
cout<<"\nPlease enter value for second function ";
cin>>name;
cout<<"\nyourname from second function is ";
cout<<name<<endl;
return 0;
}
};
int main()
{
exp b1,b2;
b2.fun1(); // removed cout
b1.fun2(); // removed cout
}
问题是您在函数内部使用 cout
,但您也在函数内部调用它们,即 cout<<b2.fun1();
。这不是一个好的做法。
还有一个问题是你的函数类型是字符串,但它们返回的是一个整数。
您还把 name
设为 public
,这恰恰违背了 OOP 的使用。所以我做到了 private
.
干杯......希望这能解决你的问题.. :)