毕竟,程序员确实定义了内部发生的事情main().
那么,它应该被视为用户定义的函数吗?
假设我的容器类中有以下方法:
Datatype& operator[](const unsigned int Index) // I know this should use size_t instead.
{
return *(BasePointer + Index); // Where BasePointer is the start of the array.
}
Run Code Online (Sandbox Code Playgroud)
我想对MyInstance[Index] = Value用法实现某种边界检查,以便当用户尝试更改其范围之外的值时,容器会自动调整大小.但是,如果用户试图访问容器范围之外的值,我想要发生其他事情,例如MyVariable = MyInstance[Index].如何检测如何operator[]使用?
假设我有一些不同类型的变量.
int MyInteger;
double MyDouble;
char MyChar;
Run Code Online (Sandbox Code Playgroud)
这些变量的指针存储在一个void指针数组中.
void* IntegerPointer = &MyInteger;
void* DoublePointer = &MyDouble;
void* CharPointer = &MyChar;
void* PointerArray[] = {IntegerPointer, DoublePointer, CharPointer};
Run Code Online (Sandbox Code Playgroud)
我想将数据类型信息存储在并行数组中. type_info似乎适合该任务,但不支持赋值.所以我不能只做这样的事情:
type_info TypeInfoArray[] = {int, double, char};
Run Code Online (Sandbox Code Playgroud)
有没有其他方法来存储有关数据类型的信息?
假设我有一个带有使用类的头文件std::string.
#include <string>
class Foo
{
std::string Bar;
public:
// ...
}
Run Code Online (Sandbox Code Playgroud)
此头文件的用户可能不希望std::string包含在他/她的项目中.那么,如何将包含限制为头文件呢?
假设我有这样一个类:
class LinkedList
{
struct Node
{
int StoredValue;
// ...
};
Node& GetNodeReference(std::size_t Index)
{
// ...
return NodeReference;
}
public:
int Get(std::size_t Index) const
{
return GetNodeReference(Index).StoredValue;
}
};
Run Code Online (Sandbox Code Playgroud)
这不会编译,因为该const方法Get使用GetNodeReference,这不能是const因为它返回一个引用.
我该如何解决这个问题?
如何在文件中删除(不替换某些)任意字符?
#include <fstream>
int main()
{
std::fstream FileStream("MyFile.txt", ios_base::in | ios_base::out | ios_base::binary);
// For the sake of argument, MyFile.txt already has stuff in it.
FileStream.seekg(5);
FileStream.remove(); // Something like this.
}
Run Code Online (Sandbox Code Playgroud) pass-by-reference函数通常如何区分pass-by-value函数?例如:
template <typename T>
void sort(std::vector<T>& source); // Sorts source.
// Versus...
template <typename T>
std::vector<T> sort(std::vector<T> source); // Returns a sorted copy of source.
Run Code Online (Sandbox Code Playgroud)
这两个功能含糊不清; 其中一个必须重命名或完全删除.
如何避免这种情况?一种形式应该优先于另一种吗?或者是否有任何共同的命名准则来区分它们?
"Bar"以下代码不是输出预期的字符串,而是输出看起来像指针的内容.
#include <sstream>
#include <iostream>
int main()
{
std::stringstream Foo("Bar");
std::cout << Foo << std::endl; // Outputs "0x22fe80."
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这可以通过使用来解决Foo.str(),但它在过去给我带来了一些问题.是什么导致这种奇怪的行为 它在哪里记录?
g++ -o Test Test.cpp -lTest
/usr/bin/ld: cannot find -lTest
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
如果在运行时按需加载共享/动态库中的符号,为什么在编译时缺少库会导致致命错误?
c++ ×8
class ×2
methods ×2
ambiguity ×1
const ×1
filestream ×1
gcc ×1
include ×1
javascript ×1
linker ×1
operators ×1
pointers ×1
reference ×1
regex ×1
return-value ×1
scope ×1
stringstream ×1
typeinfo ×1