我刚刚开始阅读C++的初学者书.我有一些java经验(但是说过,我从来没有在java中使用默认参数,说实话)
所以,如上所述,我的问题是默认参数..
这是我正在使用的代码片段:
#include <iostream>
using namespace std;
//add declaration
int add(int a, int b);
int main (void)
{
int number1;
cout << "Enter the first value to be summed: ";
cin >> number1;
cout << "\nThe sum is: " << add(number1) << endl;
}
int add(int a=10, int b=5)
{
return a+b;
}
Run Code Online (Sandbox Code Playgroud)
我从g ++编译器得到的响应是:"函数'int add(int,int)'的参数太少了
我做错了吗?(我也用文字参数尝试过)
PS我似乎无法正常显示代码片段?系统有变化吗?
因为这个问:c ++中的默认参数
说我有这样的功能: void f(int p1=1, int p2=2, int p3=3, int p4=4);
我想只使用一些参数调用它 - 其余的将是默认值.
像这样的东西会起作用:
template<bool P1=true, bool P2=true, bool P3=true, bool P4=true>
void f(int p1=1, int p2=2, int p3=3, int p4=4);
// specialize:
template<>
void f<false, true, false, false>(int p1) {
f(1, p1);
}
template<>
void f<false, true, true, false>(int p1, int p2) {
f(1, p1, p2);
}
// ... and so on.
// Would need a specialization for each combination of arguments
// which is …Run Code Online (Sandbox Code Playgroud) void doStuff( std::string const & s1, std::string const & s2="");
Run Code Online (Sandbox Code Playgroud)
我想知道这个代码在C++中是否合法,对于s2字符串.我希望有一个默认参数,但是传递一个引用并且默认为空字符串.是否会临时创建,引用会指向那个临时的,还是非法的C++?
在 Python 中处理可变默认参数的方法是将它们设置为 None。
例如:
def foo(bar=None):
bar = [] if bar is None else bar
return sorted(bar)
Run Code Online (Sandbox Code Playgroud)
如果我输入函数定义,那么唯一的类型 forbar说的bar是Optional,很明显,它不是Optional我期望sorted在其上运行该函数的时间:
def foo(bar: Optional[List[int]]=None):
bar = [] if bar is None else bar
return sorted(bar) # bar cannot be `None` here
Run Code Online (Sandbox Code Playgroud)
那么我应该投吗?
def foo(bar: Optional[List[int]]=None):
bar = [] if bar is None else bar
bar = cast(List[int], bar) # make it explicit that `bar` cannot be `None`
return sorted(bar) …Run Code Online (Sandbox Code Playgroud) 请考虑以下内容(使用Scala 2.8.1和2.9.0测试):
trait Animal
class Dog extends Animal
case class AnimalsList[A <: Animal](list:List[A] = List())
case class AnimalsMap[A <: Animal](map:Map[String,A] = Map())
val dogList = AnimalsList[Dog]() // Compiles
val dogMap = AnimalsMap[Dog]() // Does not compile
Run Code Online (Sandbox Code Playgroud)
最后一行失败了:
error: type mismatch;
found : scala.collection.immutable.Map[Nothing,Nothing]
required: Map[String,Main.Dog]
Note: Nothing <: String, but trait Map is invariant in type A.
You may wish to investigate a wildcard type such as `_ <: String`. (SLS 3.2.10)
Error occurred in an application involving default arguments. …Run Code Online (Sandbox Code Playgroud) 假设我有这个课程:
class Defaults {
def doSomething(regular: String, default: Option[String] = None) = {
println(s"Doing something: $regular, $default")
}
}
Run Code Online (Sandbox Code Playgroud)
我想检查一些其他类doSomething()在Defaults实例上调用方法而不传递第二个参数:
defaults.doSomething("abcd") // second argument is None implicitly
Run Code Online (Sandbox Code Playgroud)
但是,模拟Defaults类无法正常工作.因为方法参数的默认值在同一个类中被编译为隐藏方法,所以mock[Defaults]返回一个对象,其中这些隐藏方法返回null而不是None,因此此测试失败:
class Test extends FreeSpec with ShouldMatchers with MockitoSugar {
"Defaults" - {
"should be called with default argument" in {
val d = mock[Defaults]
d.doSomething("abcd")
verify(d).doSomething("abcd", None)
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
Argument(s) are different! Wanted:
defaults.doSomething("abcd", None);
-> at defaults.Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(Test.scala:14) …Run Code Online (Sandbox Code Playgroud) 例如,为什么我不能写这个:
void f(double x, double y = x);
Run Code Online (Sandbox Code Playgroud)
声明一个函数f,调用f(x)等效于哪个函数f(x,x)?
如果这对您没有用,那么这是一个可能的使用场景.在这个例子中,我声明f如下:
void f(double x, double y = expensiveComputation(x));
Run Code Online (Sandbox Code Playgroud)
在哪里expensiveComputation表示,你猜对了,这是一个计算速度非常慢的函数.我想给用户提供f传递y其先前计算过的值的可能性,所以我不必在里面再次计算它f.现在,我当然也可以通过编写两个重载来解决这个问题:
void f(double x, double y);
void f(double x) { f(x, expensiveComputation(x)); }
Run Code Online (Sandbox Code Playgroud)
但随着参数数量的增加,写入重载变得令人厌烦.例如,尝试写:
void f(double x, double p = expensiveComputation(x),
double q = expensiveComputation2(x, p),
double r = expensiveComputation3(x, p, q),
double s = expensiveComputation3(x, p, q, r));
Run Code Online (Sandbox Code Playgroud)
使用重载.这只是丑陋的.默认参数是性感的.是否存在更深层次的语法原因,为什么以前的参数不能用于定义参数默认值?
我希望编译以下代码:
#include <iostream>
template <class Tag = void, class T = int, class... Args>
void print(T val = T{}, Args... args) {
std::cout << val << ' ' << sizeof...(args) << std::endl;
}
int main() {
print();
print(3.14);
print(0, 1, 2);
}
Run Code Online (Sandbox Code Playgroud)
尽管有unused-but-set-parameter警告,它在GCC 5.2(C++ 11)上编译,但是clang 3.6(C++ 11)给出了以下错误消息:
main.cpp:4:33: error: missing default argument on parameter 'args'
void print(T val = T{}, Args... args) {
^
main.cpp:11:5: note: in instantiation of function template specialization 'print<void, int, int, int>' requested here …Run Code Online (Sandbox Code Playgroud) 铛编译器发出警告,下面的代码片段,可以看出这里.
clang++ -std=c++14 -O0 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp:1:18: warning: braces around scalar initializer [-Wbraced-scalar-init]
void point(int = {1}, int = {2}) {}
^~~
main.cpp:1:29: warning: braces around scalar initializer [-Wbraced-scalar-init]
void point(int = {1}, int = {2}) {}
^~~
2 warnings generated.
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
void point(int = {1}, int = {2}) {}
int main(){
point();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,{1}并且{2}是完全根据有效的默认参数[dcl.fct.default]/1,[dcl.fct]/3和[dcl.init]/1.
我想在 C++ 中创建一个简单的日志函数,它将代码位置添加到日志消息中。我想避免使用宏以及__FILE__&的使用__LINE__。
请注意,该format字符串始终是编译时字符串,我希望在编译时进行尽可能多的计算(目标机器是一个小型 MCU)。
我可以source_location通过experimental/source_location. 我也可以使用{fmt}。
我从这个开始。目前,我有以下几点:
#include <fmt/format.h>
#include <experimental/source_location>
using source_location = std::experimental::source_location;
void vlog(fmt::string_view format, fmt::format_args args)
{
fmt::vprint(format, args);
}
template <typename S, typename... Args>
void log(const S& format, const source_location& location, Args&&... args)
{
vlog(format, fmt::make_args_checked<fmt::string_view, uint32_t, Args...>(format, location.file_name(), location.line(), args...));
}
#define MY_LOG(format, ...) log(FMT_STRING("{},{}, " format), source_location::current(), __VA_ARGS__)
int main() {
MY_LOG("invalid squishiness: {}", 42);
}
Run Code Online (Sandbox Code Playgroud)
哪个产量正确./example.cpp,20, …