我一直在读Exceptional C++ by Herb Sutter
.到达时Item 32
我找到了以下内容
namespace A
{
struct X;
struct Y;
void f( int );
void g( X );
}
namespace B
{
void f( int i )
{
f( i ); // which f()?
}
}
Run Code Online (Sandbox Code Playgroud)
这个f()调用自身,具有无限递归.原因是唯一可见的f()是B :: f()本身.
还有另一个带有签名f(int)的函数,即命名空间A中的函数.如果B写了"使用命名空间A"; 或者"使用A :: f;",当查找f(int)时,A :: f(int)将作为候选者可见,并且f(i)调用在A :: f之间是不明确的( int)和B :: f(int).由于B没有将A :: f(int)带入范围,因此只能考虑B :: f(int),因此调用明确地解析为B :: f(int).
但是当我做了以下......
namespace A
{
struct X;
struct Y;
void f( int );
void g( X ); …
Run Code Online (Sandbox Code Playgroud) 是a = getchar()
相当于scanf("%c",&a);
?
是putchar(a)
等同于printf("%c",a);
其中a
是一个char
变量?
编译器是否可以检测到语义错误?如果不是,何时检测到错误?
据我所知,语义错误是由涉及操作数不正确/操作数类型的运算符的表达式产生的错误.
例如:
n3=n1*n2;//n1 is integer, n2 is a string, n3 is an integer
Run Code Online (Sandbox Code Playgroud)
上述语句在语义上是不正确的.
但在阅读Stephen Prata的C Primer Plus时,我发现了以下声明
编译器不检测语义错误,因为它们不违反C规则.编译器无法确定您的真实意图.这让你找到这些错误.一种方法是比较程序的功能与预期功能.
如果不是编译器,谁检测到这些错误?
我错过了什么吗?
第一个代码:
#include <iostream>
using namespace std;
class demo
{
int a;
public:
demo():a(9){}
demo& fun()//return type isdemo&
{
return *this;
}
};
int main()
{
demo obj;
obj.fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第二个代码:
#include <iostream>
using namespace std;
class demo
{
int a;
public:
demo():a(9){}
demo fun()//return type is demo
{
return *this;
}
};
int main()
{
demo obj;
obj.fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这两个代码有什么区别,因为两个代码都在gcc中工作?我是新来的,所以请原谅我,如果我的提问方式是错误的.
int main() {
int x = 6;
x = x+2, ++x, x-4, ++x, x+5;
std::cout << x;
}
// Output: 10
Run Code Online (Sandbox Code Playgroud)
int main() {
int x = 6;
x = (x+2, ++x, x-4, ++x, x+5);
std::cout << x;
}
// Output: 13
Run Code Online (Sandbox Code Playgroud)
请解释.
为什么这是对的?
#include<iostream>
using namespace std;
int main()
{
char *s="raman";
char *t="rawan";
s=t;
cout<<s;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但这是错的?
#include<iostream>
using namespace std;
int main()
{
char s[]="raman";
char t[]="rawan";
s=t;
cout<<s;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
c ++中的返回类型
#include<iostream>
int& fun();
int main()
{
int p=fun();
std::cout<<p;
return 0;
}
int & fun()
{
int a=10;
return &a;
}
Run Code Online (Sandbox Code Playgroud)
为什么这段代码会给出错误,错误:invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'
..实际上我不清楚临时性,即它们何时被创建以及何时被销毁.所以,请在某种程度上解释临时性.
可能重复:
当所有逗号运算符都不作为逗号运算符时?
什么时候逗号(,)表现为运算符?它什么时候表现为分隔符?它的后果是什么.如果可能,请为两者提供小例子.
#include<iostream>
#include<string.h>
using namespace std;
char * reverse (char *);
int main()
{
char * a;
cout<<"enter string"<<endl;
gets(a);
cout<<a;
cout<<"the reverse of string is"<<reverse(a);
return 0;
}
char * reverse (char * b)
{
int i,j=strlen(b);
for(i=0;b[i]!='\0';i++)
{
char temp;
temp=b[j-i-1];
b[j-i-1]=b[i];
b[i]=temp;
}
return b;
}
Run Code Online (Sandbox Code Playgroud)
该程序没有给出编译时错误.但是它确实给出了运行时错误并且没有给出所需的输出.请解释原因.由于我在C++方面不是很好,所以如果我的问题没有达到标记,请原谅我.